/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React from 'react';
import { observer } from 'mobx-react';
import {
  Modal,
  Form,
  Input,
  Select,
  message,
  Steps,
  Button,
  Divider,
  Alert,
} from 'antd';
import { http } from 'libs';
import store from './store';
import styles from './index.module.css';

@observer
class ComForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      showTmp: false,
      page: 0,
      current_tpl_id: 0,
    }
  }

  addStep = () => {
      console.log(store.templateStep)
    this.props.form.validateFields((err, values) => {
      if(!err){
        if(store.templateStep.length === 5){
          message.error('中间阶段最多添加3层')
          return
        }
        store.templateStep.push({id: this.state.current_tpl_id + 1, title: values.title, auditor: values.auditor, type: values.type})
        this.setState({current_tpl_id: this.state.current_tpl_id + 1})
      }
    })
  };
  delStep = () => {
      console.log(store.templateStep)
    const tpl_len = store.templateStep.length
    if(tpl_len !== 1 ){
      store.templateStep.splice(tpl_len-1, 1)
      this.setState({current_tpl_id: this.state.current_tpl_id - 1})
    } else {
      message.error('只有提交人节点，不可删除！');
    }
  }

  checkStep = () => {
    const end_node = store.templateStep[store.templateStep.length - 1]
    if (end_node.type !== 1) {
      message.error('最后一个节点必须为执行人节点')
      return false
    }
    return true
  }


  handleSubmit = () => {
    if(this.checkStep()){
      this.setState({loading: true});
      const formData = this.props.form.getFieldsValue();
      formData['flow'] = store.templateStep
      formData['id'] = store.record.id;
      http.post('/api/workorder/template/', formData).then(() => {
        message.success('操作成功')
        store.formVisible = false;
        store.fetchRecords();
      }, () => this.setState({loading: false}))
    } else {
      return
    }
  };

  render() {
    const info = store.record;
    const {page} = this.state;
    const {getFieldDecorator, getFieldValue} = this.props.form;
    return (
      <Modal
        visible
        width={1000}
        maskClosable={false}
        title={store.record.id ? '编辑流程模板' : '新建流程模板'}
        onCancel={() => store.formVisible = false}
        okText={store.record.id ? '更新' : '确定'}
        onOk={this.handleSubmit}
        // footer={null}
        >
        <Form labelCol={{span: 3}} wrapperCol={{span: 20}}>
          <Form.Item required label="模板名称">
            {getFieldDecorator('name', {initialValue: info['name']})(
              <Input placeholder="请输入流程模板名称"/>
            )}
          </Form.Item>
          <Form.Item label="备注">
            {getFieldDecorator('desc', {initialValue: info['desc']})(
              <Input placeholder="请输入备注"/>
            )}
          </Form.Item>
        </Form>
        <Divider orientation="left" dashed>添加阶段</Divider>
        {store.templateStep && <Steps current={page} className={styles.steps} size="small" >
          {store.templateStep.map(item => (
              <Steps.Step key={item.id} title={item.title} description={"相关人员:" + item.auditor}/>
            ))}
        </Steps>}
        <Divider orientation="left" dashed></Divider>
        <div className={styles.container}>
        <div className={styles.left}>
        <Form labelCol={{span: 5}} wrapperCol={{span: 15}}>
            <Form.Item required label="步骤类型" >
              {getFieldDecorator('type', {initialValue: info['type'], rules: [{required: true, message: '请选择步骤类型！'}] })(
                <Select placeholder="请选择步骤类型">
                  <Select.Option value={0}>审核</Select.Option>
                  <Select.Option value={1}>执行</Select.Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item required label="相关人员">
              {getFieldDecorator('auditor', {initialValue: info['auditor'], rules: [{required: true, message: '请选择相关人员！'}]})(
                <Select placeholder="请选择相关人员">
                  <Select.Option value="zhangsan">张三</Select.Option>
                  <Select.Option value="lisi">李四</Select.Option>
                  <Select.Option value="wangwu">王五</Select.Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item required label="步骤名称">
              {getFieldDecorator('title', {initialValue: info['title'], rules: [{required: true, message: '请输入步骤名称！'}]})(
                <Input placeholder="请输入步骤名称"/>
              )}
            </Form.Item>
          <Form.Item wrapperCol={{span: 15, offset: 5}}>
              <div>
                <Button  type="button"  onClick={this.addStep}>添加阶段</Button>
                <Button  type="primary" className={styles.button} onClick={this.delStep}>删除阶段</Button>
              </div>
          </Form.Item>
        </Form>
        </div>
        <div className={styles.right}>
          <Alert
          showIcon
          type="info"
          style={{width: 300, margin: '0 auto 20px', color: '#31708f !important'}}
          message="小提示"
          description={[
              <div key="1">1、中间阶段最多3个</div>,
              <div key="2">2、执行阶段只有一个</div>,
              <div key="3">2、删除阶段为删除最后一个</div>
          ]}/>
        </div>
      </div>

      </Modal>

    )
  }
}

export default Form.create()(ComForm)
